package com.itheima.interceptor;


import com.alibaba.fastjson.JSONObject;
import com.itheima.pojo.Result;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Value("${jwt.secret}")
    private String secret;
    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    /**
     localhost:8080/depts/findAll
     *  Controller执行之前先执行，返回值true false 分别代表 放行和拦截
     * @param req 请求
     * @param resp 响应
     * @param handler 处理器对象 内部包含了准备执行的Controller方法的所有信息
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws Exception {
        //2.不是登录请求，获取Token的值。
        String token = req.getHeader(tokenHeader);
        try {
            Claims body = Jwts.parser()
                    .setSigningKey(secret.getBytes())
                    .parseClaimsJws(token)
                    .getBody();
            log.info("校验token成功，放行：{}", body.get("username"));
        } catch (Exception e) {
            log.info("校验token失败，拦截");
            //3.响应数据告知浏览器，校验失败
            Result result = Result.error("NOT_LOGIN");
            //把对象转成json字符串，并响应
            String jsonString = JSONObject.toJSONString(result);
            //告诉浏览器，响应的数据以json的格式去解析，不要当成html了
            resp.setContentType("application/json;charset=utf-8");
            resp.getWriter().write(jsonString);
            return false;
        }
        return true;
    }

    /**
     *  Controller正常执行完毕，postHandle执行。Controller抛出了异常，则不执行
     * @param request 请求
     * @param response 响应
     * @param handler 处理器对象
     * @param modelAndView 模型视图对象（不常见，同步请求时代的产物，异步请求）
     * @throws Exception postHandle内部报错，编译时异常
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
       // System.out.println("postHandle");
    }

    /**
     *  一定会在最后执行的，无论前方是否报错
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
       // System.out.println("afterCompletion");
    }
}
